package com.atguigu.juc.test01;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class tongXin {
    //线程操作资源类
    public static void main(String[] args) {
        ZY zy = new ZY();

        for (int j = 0; j < 10; j++) {
            new Thread(()->{
                for (int i = 0; i < 10; i++) {
                    zy.a();
                }
            },"a"+j).start();
            new Thread(()->{
                for (int i = 0; i < 10; i++) {
                    zy.b();
                }
            },"b"+j).start();
            new Thread(()->{
                for (int i = 0; i < 10; i++) {
                    zy.c();
                }
            },"c"+j).start();
        }
    }

}
class ZY{
   private Lock lock=new ReentrantLock();
    private Condition condition1 =lock.newCondition();
    private Condition condition2 =lock.newCondition();
    private Condition condition3 =lock.newCondition();
        private int i=1;  //1=a 2=b 3=c 标志  修改 和传递
    public void a(){
       lock.lock();  // block until condition holds
            try {
                while (i!=1) condition1.await();
                System.out.println(Thread.currentThread().getName()+"   Aganh " );
                i++;
                condition2.signal();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
              lock.unlock();
            }

    };
    public void b(){
        lock.lock();  // block until condition holds
        try {
            while (i!=2) condition2.await();
            System.out.println(Thread.currentThread().getName()+"   bbbb " );
            i++;
            condition3.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    };
    public void c(){
        lock.lock();  // block until condition holds
        try {
            while (i!=3) condition3.await();
            System.out.println(Thread.currentThread().getName()+"  cccccc " );
            i=1;
            condition1.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    };


}
